package com.ruoyi.zhgd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.zhgd.annotation.ZhjdDataFilter;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.zhgd.util.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.zhgd.domain.ZjNWarningSwlq;
import com.ruoyi.zhgd.domain.ZjNWarningUserMessage;
import com.ruoyi.zhgd.domain.ZjNWarningUsing;
import com.ruoyi.zhgd.domain.bo.ZjNWarningUserMessageBo;
import com.ruoyi.zhgd.domain.vo.*;
import com.ruoyi.zhgd.mapper.ZjNWarningSwlqMapper;
import com.ruoyi.zhgd.mapper.ZjNWarningUserMessageMapper;
import com.ruoyi.zhgd.mapper.ZjNWarningUsingMapper;
import com.ruoyi.zhgd.service.IZjNWarningUsingService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.ruoyi.zhgd.domain.bo.NCementDataBo;
import com.ruoyi.zhgd.domain.NCementData;
import com.ruoyi.zhgd.mapper.NCementDataMapper;
import com.ruoyi.zhgd.service.INCementDataService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 水稳拌合站数据Service业务层处理
 *
 * @author zyb
 * @date 2023-09-06
 */
@RequiredArgsConstructor
@Service
@DS("sjcj")
public class NCementDataServiceImpl implements INCementDataService {

    private final NCementDataMapper baseMapper;

    private final ZjNWarningUsingMapper zjNWarningUsingMapper;

    private final SysDeptMapper sysDeptMapper;

    private final ZjNWarningUserMessageMapper zjNWarningUserMessageMapper;

    private final IZjNWarningUsingService iZjNWarningUsingService;

    private final ZjNWarningSwlqMapper zjNWarningSwlqMapper;

    /**
     * 查询水稳拌合站数据
     */
    @Override
    public NCementDataVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询水稳拌合站数据列表
     */
    @Override
    public TableDataInfo<NCementDataVo> queryPageList(NCementDataBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<NCementData> lqw = buildQueryWrapper(bo);
        Page<NCementDataVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询水稳拌合站数据列表
     */
    @Override
    public List<NCementDataVo> queryList(NCementDataBo bo) {
        LambdaQueryWrapper<NCementData> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<NCementData> buildQueryWrapper(NCementDataBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<NCementData> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getBaseCode()), NCementData::getBaseCode, bo.getBaseCode());
        lqw.eq(StringUtils.isNotBlank(bo.getProjectId()), NCementData::getProjectId, bo.getProjectId());
        lqw.eq(StringUtils.isNotBlank(bo.getStationCode()), NCementData::getStationCode, bo.getStationCode());
        lqw.eq(StringUtils.isNotBlank(bo.getMatchCode()), NCementData::getMatchCode, bo.getMatchCode());
        lqw.eq(bo.getDischargeTime() != null, NCementData::getDischargeTime, bo.getDischargeTime());
        lqw.eq(bo.getBatchWeight() != null, NCementData::getBatchWeight, bo.getBatchWeight());
        lqw.eq(StringUtils.isNotBlank(bo.getOriginalId()), NCementData::getOriginalId, bo.getOriginalId());
        lqw.eq(bo.getInsertTime() != null, NCementData::getInsertTime, bo.getInsertTime());
        return lqw;
    }

    /**
     * 新增水稳拌合站数据
     */
    @Override
    public Boolean insertByBo(NCementDataBo bo) {
        NCementData add = BeanUtil.toBean(bo, NCementData.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改水稳拌合站数据
     */
    @Override
    public Boolean updateByBo(NCementDataBo bo) {
        NCementData update = BeanUtil.toBean(bo, NCementData.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(NCementData entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除水稳拌合站数据
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @ZhjdDataFilter(tableAlias = "t1")
    public String getLastYear(Map<String, Object> params) {
        Date date = baseMapper.getLastDate(params);
        String result = null;
        if (null != date) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                result = sdf.format(date);
            } catch (Exception e) {
                result = null;
            }
        }
        return result;
    }

    @Override
    @ZhjdDataFilter(tableAlias = "t1")
    public PageUtils queryPage(Page page, Map<String, Object> params) {
//        List<CementProduceMonitorDto> list = baseMapper.queryPages(page, params);
        List<CementJwDataVo> list = baseMapper.page(page, params);
        List<CementJwDataPageVo> itemList = new ArrayList<>();
        List<CementJwDataPageVo> collect = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            List<CementJwDataVo> data = handleList(list);
            // 处理差值百分比
            Map<String, List<CementJwDataVo>> map = data.stream().collect(Collectors.groupingBy(CementJwDataVo::getId));
            map.forEach((key, item) -> {
                if (CollectionUtil.isNotEmpty(item)) {
                    CementJwDataPageVo cz = null;
                    CementJwDataPageVo per = null;
                    for (CementJwDataVo dataVo : item) {
                        if (ObjectUtils.isNotEmpty(dataVo) && ObjectUtils.isNotEmpty(dataVo.getDesc()) && "实际值".equals(dataVo.getDesc())) {
                            CementJwDataPageVo copy = BeanUtil.copyProperties(dataVo, CementJwDataPageVo.class);
                            itemList.add(copy);
                        }
                        if (ObjectUtils.isNotEmpty(dataVo) && ObjectUtils.isNotEmpty(dataVo.getDesc()) && "理论值".equals(dataVo.getDesc())) {
                            CementJwDataPageVo copy = BeanUtil.copyProperties(dataVo, CementJwDataPageVo.class);
                            itemList.add(copy);
                        }
                        if (ObjectUtils.isNotEmpty(dataVo) && ObjectUtils.isNotEmpty(dataVo.getDesc()) && "差值".equals(dataVo.getDesc())) {
                            cz = BeanUtil.copyProperties(dataVo, CementJwDataPageVo.class);
                        }
                        if (ObjectUtils.isNotEmpty(dataVo) && ObjectUtils.isNotEmpty(dataVo.getDesc()) && "差值百分比".equals(dataVo.getDesc())) {
                            per = BeanUtil.copyProperties(dataVo, CementJwDataPageVo.class);
                        }

                    }
                    if (ObjectUtils.isNotEmpty(cz) && ObjectUtils.isNotEmpty(per)) {
                        if (ObjectUtils.isNotEmpty(cz.getSjgl1()) && ObjectUtils.isNotEmpty(per.getSjgl1())) {
                            cz.setSjgl1(cz.getSjgl1() + "("+ per.getSjgl1() +"%)");
                        }
                        if (ObjectUtils.isNotEmpty(cz.getSjgl2()) && ObjectUtils.isNotEmpty(per.getSjgl2())) {
                            cz.setSjgl2(cz.getSjgl2() + "("+ per.getSjgl2() +"%)");
                        }
                        if (ObjectUtils.isNotEmpty(cz.getSjgl3()) && ObjectUtils.isNotEmpty(per.getSjgl3())) {
                            cz.setSjgl3(cz.getSjgl3() + "("+ per.getSjgl3() +"%)");
                        }
                        if (ObjectUtils.isNotEmpty(cz.getSjgl4()) && ObjectUtils.isNotEmpty(per.getSjgl4())) {
                            cz.setSjgl4(cz.getSjgl4() + "("+ per.getSjgl4() +"%)");
                        }
                        if (ObjectUtils.isNotEmpty(cz.getSjgl5()) && ObjectUtils.isNotEmpty(per.getSjgl5())) {
                            cz.setSjgl5(cz.getSjgl5() + "("+ per.getSjgl5() +"%)");
                        }
                        if (ObjectUtils.isNotEmpty(cz.getSjgl6()) && ObjectUtils.isNotEmpty(per.getSjgl6())) {
                            cz.setSjgl6(cz.getSjgl6() + "("+ per.getSjgl6() +"%)");
                        }
                        if (ObjectUtils.isNotEmpty(cz.getSjfl1()) && ObjectUtils.isNotEmpty(per.getSjfl1())) {
                            cz.setSjfl1(cz.getSjfl1() + "("+ per.getSjfl1() +"%)");
                        }
                        if (ObjectUtils.isNotEmpty(cz.getSjfl2()) && ObjectUtils.isNotEmpty(per.getSjfl2())) {
                            cz.setSjfl2(cz.getSjfl2() + "("+ per.getSjfl2() +"%)");
                        }
                        if (ObjectUtils.isNotEmpty(cz.getActualWater()) && ObjectUtils.isNotEmpty(per.getActualWater())) {
                            cz.setActualWater(cz.getActualWater() + "("+ per.getActualWater() +"%)");
                        }
                        if (ObjectUtils.isNotEmpty(cz.getSjbR()) && ObjectUtils.isNotEmpty(per.getSjbR())) {
                            cz.setSjbR(cz.getSjbR() + "("+ per.getSjbR() +"%)");
                        }

                        itemList.add(cz);
                    }
                }
            });
            //按出料时间倒序排；
            collect = itemList.stream().sorted((e1, e2) -> DateUtils.parseDate(e2.getOccurTime()).compareTo(DateUtils.parseDate(e1.getOccurTime()))).collect(Collectors.toList());
        }
        return new PageUtils(page.setRecords(collect));
    }

    @Override
    public List<CementJwDataVo> handleList(List<CementJwDataVo> list) {
        List<CementJwDataVo> data = new ArrayList<>();
        for (CementJwDataVo vo : list) {
            CementJwDataVo entity1 = new CementJwDataVo();
            CementJwDataVo entity2 = new CementJwDataVo();
            CementJwDataVo entity3 = new CementJwDataVo();
            CementJwDataVo entity4 = new CementJwDataVo();

            // 拌合站名称 配比编号 出料时间 批次总量 骨料123456 粉料12 水 水胶比
            // 实际值
            entity1.setId(vo.getId());
            entity1.setDeptId(vo.getDeptId());
            entity1.setDeptName(vo.getDeptName());
            entity1.setStationName(vo.getStationName());
            entity1.setOccurTime(vo.getOccurTime());
            entity1.setBaseCode(vo.getBaseCode());
            entity1.setDeptName(vo.getDeptName());
            entity1.setGlzl(vo.getGlzl());

            entity1.setDesc("实际值");
            entity1.setSjgl1(vo.getSjgl1());
            entity1.setSjgl2(vo.getSjgl2());
            entity1.setSjgl3(vo.getSjgl3());
            entity1.setSjgl4(vo.getSjgl4());
            entity1.setSjgl5(vo.getSjgl5());
            entity1.setSjgl6(vo.getSjgl6());
            entity1.setSjfl1(vo.getSjfl1());
            entity1.setSjfl2(vo.getSjfl2());
            entity1.setActualWater(vo.getActualWater());
            // 水胶比 = (粉料1+粉料2) / 水
            BigDecimal b1 = null;
            if (ObjectUtils.isNotEmpty(vo.getSjfl1()) && ObjectUtils.isNotEmpty(vo.getSjfl2()) && !(vo.getActualWater().compareTo(BigDecimal.ZERO) == 0)) {
                BigDecimal a1 = vo.getSjfl1().add(vo.getSjfl2());
                b1 = a1.divide(vo.getActualWater(), 2, BigDecimal.ROUND_HALF_UP);
                entity1.setSjbR(b1);
            }
            // 总重
            entity1.setBatchWeight(getBatchWeight(vo));

            // 理论值
            entity2.setId(vo.getId());
            entity2.setDeptId(vo.getDeptId());
            entity2.setDeptName(vo.getDeptName());
            entity2.setStationName(vo.getStationName());
            entity2.setOccurTime(vo.getOccurTime());
            entity2.setBaseCode(vo.getBaseCode());
            entity2.setDeptName(vo.getDeptName());
            entity2.setGlzl(vo.getGlzl());

            entity2.setDesc("理论值");
            entity2.setSjgl1(ObjectUtils.isNotEmpty(vo.getGlzl()) && ObjectUtils.isNotEmpty(vo.getLlgl1())
                ? vo.getLlgl1().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP).multiply(vo.getGlzl()) : null);
            entity2.setSjgl2(ObjectUtils.isNotEmpty(vo.getGlzl()) && ObjectUtils.isNotEmpty(vo.getLlgl2())
                ? vo.getLlgl2().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP).multiply(vo.getGlzl()) : null);
            entity2.setSjgl3(ObjectUtils.isNotEmpty(vo.getGlzl()) && ObjectUtils.isNotEmpty(vo.getLlgl3())
                ? vo.getLlgl3().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP).multiply(vo.getGlzl()) : null);
            entity2.setSjgl4(ObjectUtils.isNotEmpty(vo.getGlzl()) && ObjectUtils.isNotEmpty(vo.getLlgl4())
                ? vo.getLlgl4().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP).multiply(vo.getGlzl()) : null);
            entity2.setSjgl5(ObjectUtils.isNotEmpty(vo.getGlzl()) && ObjectUtils.isNotEmpty(vo.getLlgl5())
                ? vo.getLlgl5().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP).multiply(vo.getGlzl()) : null);
            entity2.setSjgl6(ObjectUtils.isNotEmpty(vo.getGlzl()) && ObjectUtils.isNotEmpty(vo.getLlgl6())
                ? vo.getLlgl6().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP).multiply(vo.getGlzl()) : null);
            entity2.setSjfl1(ObjectUtils.isNotEmpty(vo.getGlzl()) && ObjectUtils.isNotEmpty(vo.getLlfl1())
                ? vo.getLlfl1().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP).multiply(vo.getGlzl()) : null);
            entity2.setSjfl2(ObjectUtils.isNotEmpty(vo.getGlzl()) && ObjectUtils.isNotEmpty(vo.getLlfl2())
                ? vo.getLlfl2().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP).multiply(vo.getGlzl()) : null);
            entity2.setActualWater(ObjectUtils.isNotEmpty(vo.getGlzl()) && ObjectUtils.isNotEmpty(vo.getTheoreticalWater())
                ? vo.getTheoreticalWater().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP).multiply(vo.getGlzl()) : null);
            // 水胶比 = (粉料1+粉料2) / 水
            BigDecimal b2 = null;
            if (ObjectUtils.isNotEmpty(vo.getLlfl1()) && ObjectUtils.isNotEmpty(vo.getLlfl2()) && !(vo.getTheoreticalWater().compareTo(BigDecimal.ZERO) == 0)) {
                BigDecimal a2 = vo.getLlfl1().add(vo.getLlfl2());
                b2 = a2.divide(vo.getTheoreticalWater(), 2, BigDecimal.ROUND_HALF_UP);
                entity2.setSjbR(b2);
            }
            // 总重
            entity2.setBatchWeight(getBatchWeight(vo));

            // 差值
            entity3.setId(vo.getId());
            entity3.setDeptId(vo.getDeptId());
            entity3.setDeptName(vo.getDeptName());
            entity3.setStationName(vo.getStationName());
            entity3.setOccurTime(vo.getOccurTime());
            entity3.setBaseCode(vo.getBaseCode());
            entity3.setDeptName(vo.getDeptName());
            entity3.setGlzl(vo.getGlzl());

            entity3.setDesc("差值");
            entity3.setSjgl1(ObjectUtils.isNotEmpty(entity1.getSjgl1()) && ObjectUtils.isNotEmpty(entity2.getSjgl1()) && entity1.getSjgl1().compareTo(BigDecimal.ZERO) != 0 ? entity1.getSjgl1().subtract(entity2.getSjgl1()) : null);
            entity3.setSjgl2(ObjectUtils.isNotEmpty(entity1.getSjgl2()) && ObjectUtils.isNotEmpty(entity2.getSjgl2()) && entity1.getSjgl2().compareTo(BigDecimal.ZERO) != 0  ? entity1.getSjgl2().subtract(entity2.getSjgl2()) : null );
            entity3.setSjgl3(ObjectUtils.isNotEmpty(entity1.getSjgl3()) && ObjectUtils.isNotEmpty(entity2.getSjgl3()) && entity1.getSjgl3().compareTo(BigDecimal.ZERO) != 0  ? entity1.getSjgl3().subtract(entity2.getSjgl3()) : null );
            entity3.setSjgl4(ObjectUtils.isNotEmpty(entity1.getSjgl4()) && ObjectUtils.isNotEmpty(entity2.getSjgl4()) && entity1.getSjgl4().compareTo(BigDecimal.ZERO) != 0  ? entity1.getSjgl4().subtract(entity2.getSjgl4()) : null );
            entity3.setSjgl5(ObjectUtils.isNotEmpty(entity1.getSjgl5()) && ObjectUtils.isNotEmpty(entity2.getSjgl5()) && entity1.getSjgl5().compareTo(BigDecimal.ZERO) != 0  ? entity1.getSjgl5().subtract(entity2.getSjgl5()) : null );
            entity3.setSjgl6(ObjectUtils.isNotEmpty(entity1.getSjgl6()) && ObjectUtils.isNotEmpty(entity2.getSjgl6()) && entity1.getSjgl6().compareTo(BigDecimal.ZERO) != 0  ? entity1.getSjgl6().subtract(entity2.getSjgl6()) : null );
            entity3.setSjfl1(ObjectUtils.isNotEmpty(entity1.getSjfl1()) && ObjectUtils.isNotEmpty(entity2.getSjfl1()) && entity1.getSjfl1().compareTo(BigDecimal.ZERO) != 0  ? entity1.getSjfl1().subtract(entity2.getSjfl1()) : null );
            entity3.setSjfl2(ObjectUtils.isNotEmpty(entity1.getSjfl2()) && ObjectUtils.isNotEmpty(entity2.getSjfl2()) && entity1.getSjfl2().compareTo(BigDecimal.ZERO) != 0  ? entity1.getSjfl2().subtract(entity2.getSjfl2()) : null );
            entity3.setActualWater(ObjectUtils.isNotEmpty(entity1.getActualWater()) && ObjectUtils.isNotEmpty(entity2.getActualWater()) ? entity1.getActualWater().subtract(entity2.getActualWater()) : null );
            // 水胶比 = (粉料1+粉料2) / 水
            if (ObjectUtils.isNotEmpty(b1) && ObjectUtils.isNotEmpty(b2)) {
                BigDecimal b3 = b1.subtract(b2);
                entity3.setSjbR(b3);
            }
            // 总重
//                if (ObjectUtils.isNotEmpty(entity1.getBatchWeight()) && ObjectUtils.isNotEmpty(entity2.getBatchWeight())) {
//                    BigDecimal sum3 = entity1.getBatchWeight().subtract(entity2.getBatchWeight());
//                    entity3.setBatchWeight(sum3);
//                }
            entity3.setBatchWeight(getBatchWeight(vo));

            entity4.setId(vo.getId());
            entity4.setDeptId(vo.getDeptId());
            entity4.setDeptName(vo.getDeptName());
            entity4.setStationName(vo.getStationName());
            entity4.setOccurTime(vo.getOccurTime());
            entity4.setBaseCode(vo.getBaseCode());
            entity4.setDeptName(vo.getDeptName());
            entity4.setGlzl(vo.getGlzl());

            entity4.setDesc("差值百分比");
            entity4.setSjgl1(
                ObjectUtils.isNotEmpty(entity3.getSjgl1()) && ObjectUtils.isNotEmpty(entity2.getSjgl1()) && entity2.getSjgl1().compareTo(BigDecimal.ZERO) != 0
                    ? entity3.getSjgl1().divide(entity2.getSjgl1(),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)) : null);
            entity4.setSjgl2(
                ObjectUtils.isNotEmpty(entity3.getSjgl2()) && ObjectUtils.isNotEmpty(entity2.getSjgl2()) && entity2.getSjgl2().compareTo(BigDecimal.ZERO) != 0
                    ? entity3.getSjgl2().divide(entity2.getSjgl2(),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)) : null);
            entity4.setSjgl3(
                ObjectUtils.isNotEmpty(entity3.getSjgl3()) && ObjectUtils.isNotEmpty(entity2.getSjgl3()) && entity2.getSjgl3().compareTo(BigDecimal.ZERO) != 0
                    ? entity3.getSjgl3().divide(entity2.getSjgl3(),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)) : null);
            entity4.setSjgl4(
                ObjectUtils.isNotEmpty(entity3.getSjgl4()) && ObjectUtils.isNotEmpty(entity2.getSjgl4()) && entity2.getSjgl4().compareTo(BigDecimal.ZERO) != 0
                    ? entity3.getSjgl4().divide(entity2.getSjgl4(),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)) : null);
            entity4.setSjgl5(
                ObjectUtils.isNotEmpty(entity3.getSjgl5()) && ObjectUtils.isNotEmpty(entity2.getSjgl5()) && entity2.getSjgl5().compareTo(BigDecimal.ZERO) != 0
                    ? entity3.getSjgl5().divide(entity2.getSjgl5(),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)) : null);
            entity4.setSjgl6(
                ObjectUtils.isNotEmpty(entity3.getSjgl6()) && ObjectUtils.isNotEmpty(entity2.getSjgl6()) && entity2.getSjgl6().compareTo(BigDecimal.ZERO) != 0
                    ? entity3.getSjgl6().divide(entity2.getSjgl6(),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)) : null);
            entity4.setSjfl1(
                ObjectUtils.isNotEmpty(entity3.getSjfl1()) && ObjectUtils.isNotEmpty(entity2.getSjfl1()) && entity2.getSjfl1().compareTo(BigDecimal.ZERO) != 0
                    ? entity3.getSjfl1().divide(entity2.getSjfl1(),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)) : null);
            entity4.setSjfl2(
                ObjectUtils.isNotEmpty(entity3.getSjfl2()) && ObjectUtils.isNotEmpty(entity2.getSjfl2()) && entity2.getSjfl2().compareTo(BigDecimal.ZERO) != 0
                    ? entity3.getSjfl2().divide(entity2.getSjfl2(),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)) : null);
            entity4.setActualWater(
                ObjectUtils.isNotEmpty(entity3.getActualWater()) && ObjectUtils.isNotEmpty(entity2.getActualWater()) && entity2.getActualWater().compareTo(BigDecimal.ZERO) != 0
                    ? entity3.getActualWater().divide(entity2.getActualWater(),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)) : null);
            entity4.setSjbR(
                ObjectUtils.isNotEmpty(entity3.getSjbR()) && ObjectUtils.isNotEmpty(entity2.getSjbR())
                    ? entity3.getSjbR().subtract(entity2.getSjbR()) : null);

            data.add(entity1);
            data.add(entity2);
            data.add(entity3);
            data.add(entity4);
        }
        return data;
    }

    /**
     * 累加计算总重
     * @param vo
     * @return
     */
    public BigDecimal getBatchWeight(CementJwDataVo vo) {
        BigDecimal sum = BigDecimal.ZERO;
        if (ObjectUtils.isNotEmpty(vo.getSjgl1())) {
            sum = sum.add(vo.getSjgl1());
        }
        if (ObjectUtils.isNotEmpty(vo.getSjgl2())) {
            sum = sum.add(vo.getSjgl2());
        }
        if (ObjectUtils.isNotEmpty(vo.getSjgl3())) {
            sum = sum.add(vo.getSjgl3());
        }
        if (ObjectUtils.isNotEmpty(vo.getSjgl4())) {
            sum = sum.add(vo.getSjgl4());
        }
        if (ObjectUtils.isNotEmpty(vo.getSjgl5())) {
            sum = sum.add(vo.getSjgl5());
        }
        if (ObjectUtils.isNotEmpty(vo.getSjgl6())) {
            sum = sum.add(vo.getSjgl6());
        }
        if (ObjectUtils.isNotEmpty(vo.getSjfl1())) {
            sum = sum.add(vo.getSjfl1());
        }
        if (ObjectUtils.isNotEmpty(vo.getSjfl2())) {
            sum = sum.add(vo.getSjfl2());
        }
        if (ObjectUtils.isNotEmpty(vo.getActualWater())) {
            sum = sum.add(vo.getActualWater());
        }
        return sum;
    }

    /**
     * 生产质量监控
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<NCementDataVo> pageQuality(NCementDataBo bo, PageQuery pageQuery) {
        return TableDataInfo.build(baseMapper.pageQuality(bo, pageQuery.build()));
    }

    /**
     * 获取质量汇总分析数据分页列表
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<NCementDataQualityStatisticsVo> pageQualityStatistics(NCementDataBo bo, PageQuery pageQuery) {
        return TableDataInfo.build(baseMapper.pageQualityStatistics(bo, pageQuery.build()));
    }

    /**
     * 总量校核
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<NCementProduceWeightVo> pageCheck(NCementDataBo bo, PageQuery pageQuery) {
        return TableDataInfo.build(baseMapper.pageCheck(bo, pageQuery.build()));
    }

    /**
     * 水稳产量统计汇总
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<NCementOutputSummaryVo> pageOutputStatistics(NCementDataBo bo, PageQuery pageQuery) {
        return TableDataInfo.build(baseMapper.pageOutputStatistics(bo, pageQuery.build()));
    }

    /**
     * 获取最新一条数据
     * @param params
     * @return
     */
    @Override
    public NCementDataVo getLastData(Map<String, Object> params) {
        QueryWrapper<NCementData> queryWrapper = new QueryWrapper<>();
        if(ObjectUtils.isNotEmpty(params.get("baseCode"))) {
            queryWrapper.eq("base_code", params.get("baseCode").toString());
        }
        if(ObjectUtils.isNotEmpty(params.get("stationCode"))) {
            queryWrapper.eq("station_code", params.get("stationCode").toString());
        }
        if(ObjectUtils.isNotEmpty(params.get("matchType"))) {
            queryWrapper.eq("match_type", params.get("matchType").toString());
        }
        if(ObjectUtils.isNotEmpty(params.get("matchName"))) {
            queryWrapper.eq("match_name", params.get("matchName").toString());
        }
        if(ObjectUtils.isNotEmpty(params.get("matchCode"))) {
            queryWrapper.eq("match_code", params.get("matchCode").toString());
        }
        if(ObjectUtils.isNotEmpty(params.get("day"))) {
            queryWrapper.eq("DATE_FORMAT( discharge_time, '%Y-%m-%d' )", params.get("day").toString());
        }
        queryWrapper.orderByDesc("discharge_time");
        queryWrapper.last(" limit 1 ");
        return baseMapper.selectVoOne(queryWrapper);
    }

    /**
     * 水稳项目产量统计
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<NCementProjectStatisticsListVo> pageProjectStatistics(NCementDataBo bo, PageQuery pageQuery) {
        return TableDataInfo.build(baseMapper.pageProjectStatistics(bo, pageQuery.build()));
    }

    /**
     * 水稳材料消耗
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<NCementMaterielConsumeVo> pageMaterielConsume(NCementDataBo bo, PageQuery pageQuery) {
        return TableDataInfo.build(baseMapper.pageMaterielConsume(bo, pageQuery.build()));
    }

    /**
     * 获取最新数据日期
     *
     * @param params
     * @return
     */
    @Override
    public String getLastDay(Map<String, Object> params) {
        Date date = baseMapper.getLastDate(params);
        String result = null;
        if (ObjectUtils.isNotEmpty(date)) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                result = sdf.format(date);
            } catch (Exception e) {
                result = null;
            }
        }
        return result;
    }

    /**
     * 历年产量数据
     *
     * @param bo
     * @return
     */
    @Override
    public List<NCementOutputStatisticsVo> listForYear(NCementDataBo bo) {
        return baseMapper.listForYear(bo);
    }

    /**
     * 月产量数据
     *
     * @param bo
     * @return
     */
    @Override
    public List<NCementOutputStatisticsVo> listForMonth(NCementDataBo bo) {
        return baseMapper.listForMonth(bo);
    }

    /**
     * 日产量数据
     *
     * @param bo
     * @return
     */
    @Override
    public List<NCementOutputStatisticsVo> listForDay(NCementDataBo bo) {
        return baseMapper.listForDay(bo);
    }

    /**
     * 项目产量数据
     *
     * @param bo
     * @return
     */
    @Override
    public List<NCementOutputStatisticsVo> listForProject(NCementDataBo bo) {
        return baseMapper.listForProject(bo);
    }

    /**
     * 配方产量数据
     *
     * @param bo
     * @return
     */
    @Override
    public List<NCementOutputStatisticsVo> listForMatch(NCementDataBo bo) {
        return baseMapper.listForMatch(bo);
    }

    private String status = null; // 合格状态 0 不合格 1 合格
    private List<Object> unqualifiedParams = new ArrayList<>(); // 不合格参数

    /**
     * 手动校验
     *
     * @param bo
     */
    @Override
    public void handCheck(NCementDataBo bo) {
        if (ObjectUtils.isEmpty(bo.getIds())) {
            throw new ServiceException("ID列表不能为空");
        }
        // 根据ids查询水稳拌合站生产数据
        List<NCementDataCheckVo> vos = baseMapper.getByIds(bo.getIds());
        if (CollectionUtils.isNotEmpty(vos)) {
            // 根据上下限判断是否合格
            List<NCementData> recUpdateList = new ArrayList<>();
            estimateData(vos, recUpdateList);
        }
    }

    @Transactional
    public void estimateData(List<NCementDataCheckVo> vos, List<NCementData> recUpdateList) {
        unqualifiedParams = new ArrayList<>();
        for (NCementDataCheckVo vo : vos) {
            if (vo.getBatchWeight().compareTo(BigDecimal.ZERO) != 0) {
                // 实际值
                // 获取水泥含量实际占比=(水泥1+水泥2)/总量
                BigDecimal snRActual = (vo.getPowder1Act().add(vo.getPowder2Act())).divide(vo.getBatchWeight(), 2, BigDecimal.ROUND_HALF_UP);
                // 获取水含量实际占比=水含量/总量
                BigDecimal waterRActual = vo.getWaterAct().divide(vo.getBatchWeight(), 2, BigDecimal.ROUND_HALF_UP);
                // 获取水胶比=水含量/水泥含量
                BigDecimal sjbRActual = BigDecimal.ZERO;
                if ((vo.getPowder1Act().add(vo.getPowder2Act())).compareTo(BigDecimal.ZERO) != 0) {
                    sjbRActual = vo.getWaterAct().divide(vo.getPowder1Act().add(vo.getPowder2Act()), 2, BigDecimal.ROUND_HALF_UP);
                }
                // 理论值
                // 配比百分比转实际小数值
                BigDecimal water = vo.getWater().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                BigDecimal powder1 = vo.getPowder1().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                BigDecimal powder2 = vo.getPowder2().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                // 水胶比上下限理论范围
                BigDecimal powder = powder1.add(powder2);
                BigDecimal sjbMaxDesign = BigDecimal.ZERO;
                BigDecimal sjbMinDesign = BigDecimal.ZERO;
                if (powder.compareTo(BigDecimal.ZERO) != 0) {
                    sjbMaxDesign = water.divide(powder.multiply(BigDecimal.ONE.add(vo.getSjbMaxVal())));
                    sjbMinDesign = water.divide(powder.multiply(BigDecimal.ONE.subtract(vo.getSjbMinVal())));
                }
                // 水含量上下限理论范围
                BigDecimal waterMaxDesign = water.multiply(BigDecimal.ONE.add(vo.getWaterMaxVal()));
                BigDecimal waterMinDesign = water.multiply(BigDecimal.ONE.subtract(vo.getWaterMinVal()));
                // 水泥上下限理论范围
                BigDecimal snMaxDesign = (powder1.add(powder2)).multiply(BigDecimal.ONE.add(vo.getSnMaxVal()));
                BigDecimal snMinDesign = (powder1.add(powder2)).multiply(BigDecimal.ONE.subtract(vo.getSnMinVal()));
                // 判断 水胶比 水含量 水泥含量是否在上下限范围内
                if (!(snRActual.compareTo(snMinDesign) != -1 && waterRActual.compareTo(snMaxDesign) != 1)) {
                    // 不合格
                    status= "0";
                    vo.setStatus("0");
                    unqualifiedParams.add("水泥掺量外掺占比:"
                        + snRActual.multiply(new BigDecimal(100)).setScale(1, BigDecimal.ROUND_HALF_UP) + "%"
                        + "超出上下限范围(" + snMinDesign + "%" + "~" + snMaxDesign + "%" +")");
                }
                else if (!(waterRActual.compareTo(waterMinDesign) != -1 && waterRActual.compareTo(waterMaxDesign) != 1)) {
                    // 不合格
                    status= "0";
                    vo.setStatus("0");
                    unqualifiedParams.add("水含量占比:"
                        + waterRActual.multiply(new BigDecimal(100)).setScale(1, BigDecimal.ROUND_HALF_UP) + "%"
                        + "超出上下限范围(" + snMinDesign + "%" + "~" + waterMaxDesign + "%" +")");
                }
                else if (!(sjbRActual.compareTo(sjbMinDesign) != -1 && sjbRActual.compareTo(sjbMaxDesign) != 1)) {
                    // 不合格
                    status= "0";
                    vo.setStatus("0");
                    unqualifiedParams.add("水胶比:"
                        + sjbRActual.multiply(new BigDecimal(100)).setScale(1, BigDecimal.ROUND_HALF_UP) + "%"
                        + "超出上下限范围(" + sjbMinDesign + "%" + "~" + sjbMaxDesign + "%" +")");
                }
                else {
                    // 合格
                    status = "1";
                    vo.setStatus("1");
                }
                // 创建更新对象
                NCementData entity = new NCementData();
                entity.setId(vo.getId());
                entity.setStatus(status);
                recUpdateList.add(entity);
            }
            // 保存并推送消息
            if (ObjectUtils.isNotEmpty(vo.getDeptId())) {
                sendMsg(vo.getDeptId(), vo, 0);
            } else {
                throw new ServiceException("没有查询到部门信息,无法推送消息!");
            }
        }
        // 更新主表状态
        if (CollectionUtils.isNotEmpty(recUpdateList) && recUpdateList.size() > 0) {
            baseMapper.updateBatchById(recUpdateList);
        }
    }

    private void sendMsg(String deptId, NCementDataCheckVo vo, int isSend) {
        String message = null;
        int send = 1;
        // 是否发送消息 1发送 0不发
        if (isSend == 1) {
            // 根据deptId获取祖级列表
            SysDept dept = sysDeptMapper.getById(Long.valueOf(deptId));
            String ancestors = com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(dept) ? dept.getAncestors() : null;
            String[] ids = com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(ancestors) ? ancestors.split(",") : new String[]{} ;
            // 根据部门id获取预警标识
            ZjNWarningUsing entity = zjNWarningUsingMapper.getByDeptId(deptId, ids);
            Long msgSw = com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(entity) ? entity.getUsingMsgSw() : 0;
            if (msgSw == 1 && !"1".equals(status)) {
                // 发送人获取:
                ZjNWarningUserMessageBo bo = new ZjNWarningUserMessageBo();
                bo.setId(deptId);
                QueryWrapper<ZjNWarningUserMessage> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("a.del_flag", "0");
                wrapper1.eq("u.del_flag", "0");
                wrapper1.isNotNull("a.warn_val_sw");
                List<ZjNWarningUserMessageVo> list = zjNWarningUserMessageMapper.getZlyjList(wrapper1, bo);
                List<String> phonenumber = list.stream().map(ZjNWarningUserMessageVo::getPhonenumber).collect(Collectors.toList());
                // 发送内容:
                // 短信推送样例：【山东高速】xx标段，xx拌合站的xx施工部位采用的xx配方的外加剂1产生了初级预警,超出标准值或低于标准值xx%。
                String deptName = ObjectUtils.isNotEmpty(vo.getDeptName()) ? "【" + vo.getDeptName() : "【";
                String projectName = ObjectUtils.isNotEmpty(vo.getProjectName()) ? vo.getProjectName() : "";
                String stationName = ObjectUtils.isNotEmpty(vo.getStationName()) ? vo.getStationName() : "";
                String matchCode = "配比编号:" + (ObjectUtils.isNotEmpty(vo.getStationName()) ? vo.getStationName() : "");
                String dischargeTime = "出料时间:" + (ObjectUtils.isNotEmpty(vo.getStationName()) ? vo.getStationName() : "");
                String batchWeight = "盘重:" + (ObjectUtils.isNotEmpty(vo.getBatchWeight()) ? vo.getBatchWeight() : "");
                String start = "";
                String separator = " ";
                String common = "】的水稳数据产生了预警信息: ";
                // 不合格参数
                String params = "";
                for (Object str : unqualifiedParams) {
                    params += str;
                }
                params += "不合格;";
                message =  start + deptName + separator + projectName + separator + stationName + separator  + matchCode + separator + dischargeTime + separator + batchWeight + common + params;
                // 预警发送及保存
                try {
                    send = iZjNWarningUsingService.send(phonenumber, message);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("短信发送失败");
                }
            }
        }
        // 不合格则产生预警信息
        if (!"1".equals(status)) {
            ZjNWarningSwlq entity = new ZjNWarningSwlq();
            entity.setType("1"); // 水稳
            entity.setInsterTime(new Date());
            entity.setRemark(message);
            entity.setBusinessId(vo.getId());
            entity.setStatus(String.valueOf(send));
            zjNWarningSwlqMapper.insert(entity);
        }
    }
}
